package com.example.demo.controller;


import ch.qos.logback.classic.Logger;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Utils.JwtUtils;
import com.example.demo.common.Result;
import com.example.demo.dto.DepartmentWithDishesDTO;
import com.example.demo.entity.Department;
import com.example.demo.entity.Dish;
import com.example.demo.service.DepartmentService;
import com.example.demo.service.DishService;
import com.example.demo.service.RestaurantService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/departments")
public class DepartmentController {
    ch.qos.logback.classic.Logger logger = (Logger) LoggerFactory.getLogger(RestaurantController.class);
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RestaurantService restaurantService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private DishService dishService;
    @GetMapping
    public Result<List<Department>> getAllDepartments(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Integer restaurantId) {

        // 允许restaurantId为空时的查询
        if (restaurantId == null) {
            return Result.success(departmentService.list());
        }

        // 强化参数校验
        if (restaurantId <= 0) {
            return (Result<List<Department>>) Result.error(400, "餐厅ID必须为正整数");
        }

        QueryWrapper<Department> query = new QueryWrapper<>();
        query.eq("restaurant_id", restaurantId);
        return Result.success(departmentService.list(query));
    }
    // DepartmentController.java
    @PostMapping
    public Result<?> addDepartment(
            @RequestHeader("Authorization") String token,
            @RequestBody Department department) {

        // 鉴权校验
        if (!jwtUtils.validateToken(token.replace("Bearer ", ""))) {
            return Result.error(401, "无效的Token");
        }

        // 手动参数校验
        if (department.getName() == null || department.getName().trim().isEmpty()) {
            return Result.error(400, "部门名称不能为空");
        }
        if (department.getRestaurantId() == null) {
            return Result.error(400, "必须关联餐厅");
        }

        // 检查餐厅是否存在
        if (!restaurantService.existsById(department.getRestaurantId())) {
            return Result.error(400, "关联餐厅不存在");
        }

        return departmentService.save(department)
                ? Result.success(department)
                : Result.error(500, "保存失败");
    }
    // DepartmentController.java
    @DeleteMapping("/{id}")
    public Result<?> deleteDepartment(
            @RequestHeader("Authorization") String token,
            @PathVariable Integer id) {

        // 添加权限校验
        if (!jwtUtils.validateToken(token.replace("Bearer ", ""))) {
            return Result.error(401, "无效的Token");
        }

        // 优化级联查询
        Long dishCount = dishService.count(
                new QueryWrapper<Dish>()
                        .select("id")
                        .eq("department_id", id)
                        .last("LIMIT 1")
        );

        if (dishCount > 0) {
            return Result.error(409, "请先删除该部门下的所有菜品");
        }

        return departmentService.removeById(id)
                ? Result.success()
                : Result.error(500, "删除失败");
    }
    @PutMapping("/{id}")
    public Result<?> updateDepartment(
            @PathVariable Integer id,
            @RequestBody Department department) {

        // ID有效性校验
        if (id == null || id <= 0) {
            return Result.error(400, "无效的部门ID");
        }

        // 检查部门是否存在
        Department existDept = departmentService.getById(id);
        if (existDept == null) {
            return Result.error(404, "部门不存在");
        }

        // 名称校验
        if (department.getName() != null) {
            String name = department.getName().trim();
            if (name.isEmpty()) {
                return Result.error(400, "部门名称不能为空");
            }
            existDept.setName(name);
        }

        // 餐厅关联校验
        if (department.getRestaurantId() != null) {
            if (!restaurantService.existsById(department.getRestaurantId())) {
                return Result.error(400, "关联餐厅不存在");
            }
            existDept.setRestaurantId(department.getRestaurantId());
        }

        return departmentService.updateById(existDept)
                ? Result.success()
                : Result.error(500, "更新失败");
    }
    @PutMapping("/{id}/with-dishes")
    public Result<?> updateDepartmentWithDishes(
            @PathVariable Integer id,
            @RequestBody @Validated DepartmentWithDishesDTO dto) {

        // 更新部门信息
        Department department = new Department();
        department.setId(id);
        department.setName(dto.getName());
        departmentService.updateById(department);

        // 更新菜品信息
        List<Dish> dishes = dto.getDishes().stream().map(dishDTO -> {
            Dish dish = new Dish();
            dish.setId(dishDTO.getId());
            dish.setName(dishDTO.getName());
            dish.setPrice(dishDTO.getPrice());
            dish.setQuantity(dishDTO.getQuantity()); // 新增数量设置
            dish.setDepartmentId(id);
            return dish;
        }).collect(Collectors.toList());

        dishService.updateBatchById(dishes);

        return Result.success();
    }
    // 新增获取部门及菜品接口
    @GetMapping("/{id}/with-dishes")
    public Result<DepartmentWithDishesDTO> getDepartmentWithDishes(
            @PathVariable Integer id,
            @RequestHeader("Authorization") String token) {

        // 鉴权校验
        if (!jwtUtils.validateToken(token.replace("Bearer ", ""))) {
            return (Result<DepartmentWithDishesDTO>) Result.error(401, "无效的Token");
        }

        Department department = departmentService.getById(id);
        if (department == null) {
            return (Result<DepartmentWithDishesDTO>) Result.error(404, "部门不存在");
        }

        List<Dish> dishes = dishService.list(
                new QueryWrapper<Dish>().eq("department_id", id)
        );

        DepartmentWithDishesDTO dto = new DepartmentWithDishesDTO();
        dto.setId(department.getId());
        dto.setName(department.getName());
        dto.setDishes(dishes.stream().map(dish -> {
            DepartmentWithDishesDTO.DishDTO dishDTO = new DepartmentWithDishesDTO.DishDTO();
            dishDTO.setId(dish.getId());
            dishDTO.setName(dish.getName());
            dishDTO.setPrice(dish.getPrice());
            return dishDTO;
        }).collect(Collectors.toList()));

        return Result.success(dto);
    }
}